from   myapp                         import app
from   behave                        import *
from   selenium.webdriver.common.by  import By
from   selenium.webdriver.support.ui import WebDriverWait
from   selenium.webdriver.support    import expected_conditions as EC
from   selenium.common.exceptions    import TimeoutException
import os
import traceback

exec(open(app.root_path + '/constants/tests_constants.py').read())


def get_route(model , action = ''):
  if action in ACTIONS: action = ACTIONS[action]

  return SERVER_URL + CONTROLLERS[model] + action


@given(u'I am on the "{page_name}" page')
@when(u'I browse to the "{page_name}" page')
def am_on_some_page(context , page_name):
  context.execute_steps('when I browse to "' + get_route(page_name) + '"')


@then(u'I should be on the "{page_name}" page')
def should_be_on_some_page(context , page_name):
  assert context.browser.current_url == get_route(page_name)


@then(u'I should be on the "{action}" "{model}" CRUD page')
def should_be_on_a_crud_page(context , action , model):
  print("url=" + context.browser.current_url )
  print("route=" + get_route(model , action))

  actual_url   = os.path.normpath(context.browser.current_url)
  expected_url = os.path.normpath(get_route(model , action))
  assert actual_url == expected_url


@when(u'I login as user: "{login}" with password: "{password}"')
def submit_login_form(context , login , password):
  login_input = context.browser.find_element_by_name(LOGIN_INPUT_NAME).send_keys(login   )
  pass_input  = context.browser.find_element_by_name(PASS_INPUT_NAME ).send_keys(password)
  login_btn   = context.browser.find_element_by_name(LOGIN_BTN_NAME  )

  try:
    login_btn.click()
    WebDriverWait(context.browser , 35).until(EC.staleness_of(login_btn))
    WebDriverWait(context.browser , 35).until(EC.presence_of_element_located((By.TAG_NAME , 'html')))
  except(TimeoutException): traceback.print_exc()


@when(u'I login with bogus credentials')
def i_login_with_bogus_credentials(context):
  context.execute_steps('when I login as user: "abc" with password: "xyz"')


@when(u'I login as the admin')
def i_login(context):
  context.execute_steps('when I login as user: "' + ADMIN_LOGIN + '" with password: "' + ADMIN_PASS + '"')


#@then(u'I should be signed in')
#def am_signed_in(context):
  #pass
